//
//  FBPlayView.m
//  MusicForChilden
//
//  Created by qlydfb on 2021/10/29.
//

#import "FBPlayView.h"
#import <FreeStreamer/FSAudioController.h>
#import "FBVideoDetailMdeol.h"
#import "FBVideoListModel.h"
#import <AVFoundation/AVFoundation.h>
#import <MediaPlayer/MediaPlayer.h>

@interface FBPlayView()
@property(strong, nonatomic)UIImageView *imgs;
@property(strong, nonatomic)UILabel *nameLbl;
@property(strong, nonatomic)UIProgressView *progress;
@property(strong, nonatomic)UILabel *startTime;
@property(strong, nonatomic)UILabel *endTime;
@property(strong, nonatomic)UIButton *playBtn;
@property(strong, nonatomic)UIButton *blockBtn;//循环
@property(strong, nonatomic)FSAudioController *audioController;
@property(strong, nonatomic)NSTimer *playTime;
@property(strong, nonatomic)FBVideoDetailMdeol *playModel;
@property(strong, nonatomic)FBVideoListDetailMode *videoInfo;

@end

@implementation FBPlayView
- (instancetype)initWithFrame:(CGRect)frame{
    if(self = [super initWithFrame:frame]){
        
        [self initWithView];
    }
    return self;
}
- (void)initWithView{
    AVAudioSession *session = [AVAudioSession sharedInstance];
    [session setActive:YES error:nil];
    [session setCategory:AVAudioSessionCategoryPlayback error:nil];
    self.backgroundColor = [UIColor whiteColor];
    self.imgs = [[UIImageView alloc]initWithFrame:self.bounds];
    self.imgs.contentMode = UIViewContentModeScaleAspectFit;
    [self addSubview:self.imgs];
    [self.imgs mas_makeConstraints:^(MASConstraintMaker *make) {
       make.top.mas_equalTo(20) ;
        make.centerX.mas_equalTo(self.mas_centerX);
        make.size.mas_equalTo(CGSizeMake(60, 60));
    }];
    self.nameLbl = [[UILabel alloc]init];
    self.nameLbl.font = [UIFont systemFontOfSize:16];
    self.nameLbl.textColor = [UIColor blackColor];
    self.nameLbl.textAlignment = NSTextAlignmentCenter;
    [self addSubview:self.nameLbl];
    [self.nameLbl mas_makeConstraints:^(MASConstraintMaker *make) {
       make.centerX.mas_equalTo(self.imgs.mas_centerX) ;
        make.top.mas_equalTo(self.imgs.mas_bottom).offset(10);
    }];
    self.startTime = [[UILabel alloc]init];
    self.startTime.backgroundColor = [UIColor clearColor];
    self.startTime.font = [UIFont systemFontOfSize:12];
    self.startTime.textColor = [UIColor redColor];
    self.startTime.alpha = 0.6;
    [self addSubview:self.startTime];
    [self.startTime mas_makeConstraints:^(MASConstraintMaker *make) {
       make.left.mas_equalTo(16) ;
        make.top.mas_equalTo(self.nameLbl.mas_bottom).offset(10);
    }];
    self.endTime = [[UILabel alloc]init];
    self.endTime.backgroundColor = [UIColor clearColor];
    self.endTime.font = [UIFont systemFontOfSize:12];
    self.endTime.textColor = [UIColor redColor];
    self.endTime.alpha = 0.6;
    [self addSubview:self.endTime];
    [self.endTime mas_makeConstraints:^(MASConstraintMaker *make) {
       make.right.mas_equalTo(-16) ;
        make.centerY.mas_equalTo(self.startTime.mas_centerY);
    }];
    self.progress = [[UIProgressView alloc]initWithProgressViewStyle:UIProgressViewStyleBar];
    self.progress.backgroundColor = [UIColor clearColor];
    self.progress.progressTintColor = [UIColor redColor];
    self.progress.trackTintColor = [UIColor colorWithWhite:0 alpha:0.4];
    [self addSubview:self.progress];
    [self.progress mas_makeConstraints:^(MASConstraintMaker *make) {
       make.left.mas_equalTo(self.startTime.mas_right).offset(6)     ;
        make.right.mas_equalTo(self.endTime.mas_left).offset(-6);
        make.centerY.mas_equalTo(self.startTime.mas_centerY);
        make.height.mas_equalTo(4);
    }];
    self.playBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    self.playBtn.backgroundColor = [UIColor clearColor];
    [self.playBtn setImage:[UIImage imageNamed:@"playBtn"] forState:UIControlStateNormal];
    [self.playBtn setImage:[UIImage imageNamed:@"puaseBtn"] forState:UIControlStateSelected];
    self.playBtn.imageView.contentMode = UIViewContentModeScaleAspectFit;
    [self addSubview:self.playBtn];
    [self.playBtn mas_makeConstraints:^(MASConstraintMaker *make) {
       make.centerX.mas_equalTo(self.mas_centerX);
        make.top.mas_equalTo(self.progress.mas_bottom).offset(20);
        make.size.mas_equalTo(CGSizeMake(64, 64));
    }];
    [self.playBtn addTarget:self action:@selector(onClickOfButton:) forControlEvents:UIControlEventTouchUpInside];
    
}
- (FSAudioController *)audioController{
    if(!_audioController){
        _audioController = [[FSAudioController alloc]init];
        __weak typeof(self) ws = self;
        _audioController.onStateChange = ^(FSAudioStreamState state) {
            NSLog(@"FSAudioStreamState=%zd",state);

            if(state == kFsAudioStreamPlaying){
                [[NSRunLoop currentRunLoop] addTimer:ws.playTime forMode:NSRunLoopCommonModes];
            }else if(state == kFsAudioStreamPlaybackCompleted){
                [ws.playTime invalidate];
                ws.playTime = nil;
            }
        };
        _audioController.onMetaDataAvailable = ^(NSDictionary *metadata) {
            NSLog(@"metadata=%@",metadata);
        };
    }
    return _audioController;
}
-(void)onClickOfButton:(UIButton *)sender{
    sender.selected = !sender.selected;
    if(sender.selected)
    [self.audioController playFromURL:[NSURL URLWithString:self.playModel.audioUrl]];
    else
        [self.audioController pause];
}
- (NSTimer *)playTime{
    if(!_playTime){
        _playTime = [NSTimer timerWithTimeInterval:1 target:self selector:@selector(updatePlaybackProgress) userInfo:nil repeats:YES];
        [[NSRunLoop currentRunLoop] addTimer:_playTime forMode:NSRunLoopCommonModes];
    }
    return _playTime;
}
- (void)updatePlaybackProgress{
    if (self.audioController.activeStream.continuous) {
        } else {
            FSStreamPosition cur = self.audioController.activeStream.currentTimePlayed;
            FSStreamPosition end = self.audioController.activeStream.duration;
            CGFloat loadTime = cur.minute *60 + cur.second;
            CGFloat totalTime = end.minute*60 + end.second;
            NSString *loadDate = [NSString stringWithFormat:@"%i:%02i",cur.minute, cur.second];
            NSString *totalDate = [NSString stringWithFormat:@"%i:%02i",end.minute, end.second];
            dispatch_async(dispatch_get_main_queue(), ^{
                [self.progress setProgress:loadTime/totalTime animated:YES];
                self.startTime.text = loadDate;
                self.endTime.text = totalDate;;
            });

        }
}
- (void)playViewInfo:(FBVideoDetailMdeol *)playModel videoInfo:(nonnull FBVideoListDetailMode *)videoInfo{
    self.playModel = playModel;
    self.videoInfo = videoInfo;
    [self.imgs sd_setImageWithURL:[NSURL URLWithString:videoInfo.cover] placeholderImage:[UIImage imageNamed:@"default"]];
    self.nameLbl.text = videoInfo.title;
    [self onClickOfButton:self.playBtn];
    [self setLockScreenInfo];
}
///设置锁屏信息
-(void)setLockScreenInfo
{
    // MPMediaItemPropertyAlbumTitle
    // MPMediaItemPropertyAlbumTrackCount
    // MPMediaItemPropertyAlbumTrackNumber
    // MPMediaItemPropertyArtist
    // MPMediaItemPropertyArtwork
    // MPMediaItemPropertyComposer
    // MPMediaItemPropertyDiscCount
    // MPMediaItemPropertyDiscNumber
    // MPMediaItemPropertyGenre
    // MPMediaItemPropertyPersistentID
    // MPMediaItemPropertyPlaybackDuration
    // MPMediaItemPropertyTitle

    //获取锁屏中心
    MPNowPlayingInfoCenter *playCenter = [MPNowPlayingInfoCenter defaultCenter];
    
    NSMutableDictionary *infoDict = [NSMutableDictionary dictionary];
    //设置歌曲名
    infoDict[MPMediaItemPropertyAlbumTitle] = _videoInfo.title;
    //设置歌手名
    infoDict[MPMediaItemPropertyArtist] = _videoInfo.title;
    //设置图片
    MPMediaItemArtwork *artWork = [[MPMediaItemArtwork alloc]initWithBoundsSize:CGSizeMake(100, 100) requestHandler:^UIImage * _Nonnull(CGSize size) {
        return self.imgs.image;
    }];//:self.imgs.image];
    
    infoDict[MPMediaItemPropertyArtwork] = artWork;
    FSStreamPosition end = self.audioController.activeStream.duration;

    //设置总时长
    infoDict[MPMediaItemPropertyPlaybackDuration] = @(end.second);
    
    playCenter.nowPlayingInfo = infoDict;
    //开启远程控制
    [[UIApplication sharedApplication]beginReceivingRemoteControlEvents];
}

///远程控制
-(void)remoteControlReceivedWithEvent:(UIEvent *)event
{
//    UIEventSubtypeRemoteControlPlay                 = 100,
//    UIEventSubtypeRemoteControlPause                = 101,
//    UIEventSubtypeRemoteControlStop                 = 102,
//    UIEventSubtypeRemoteControlTogglePlayPause      = 103,
//    UIEventSubtypeRemoteControlNextTrack            = 104,
//    UIEventSubtypeRemoteControlPreviousTrack        = 105,
//    UIEventSubtypeRemoteControlBeginSeekingBackward = 106,
//    UIEventSubtypeRemoteControlEndSeekingBackward   = 107,
//    UIEventSubtypeRemoteControlBeginSeekingForward  = 108,
//    UIEventSubtypeRemoteControlEndSeekingForward    = 109,
    
    switch (event.subtype) {
        case UIEventSubtypeRemoteControlPlay:
        case UIEventSubtypeRemoteControlPause:
            [self.audioController play];
            break;
        case UIEventSubtypeRemoteControlNextTrack:
            if(self.playAction){
                self.playAction(2);
            }
            //[self next:nil];
            break;
        case UIEventSubtypeRemoteControlPreviousTrack:
            if(self.playAction){
                self.playAction(1);
            }
           // [self previous:nil];
            break;
        default:
            break;
    }
    
    
}
/*
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.
- (void)drawRect:(CGRect)rect {
    // Drawing code
}
*/

@end
